// 2013-7-29下午06:00:55  net.betou.trade.main.dao.impl.NoticeDaoImpl.java

package net.betou.trade.main.dao.impl;

import java.util.List;

import net.betou.common.hibernate3.Finder;
import net.betou.common.hibernate3.HibernateBaseDao;
import net.betou.common.page.Pagination;
import net.betou.trade.entity.main.Notice;
import net.betou.trade.main.dao.NoticeDao;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;

/**
 * 
 * @author 叶装装
 */
@Repository
public class NoticeDaoImpl extends HibernateBaseDao< Notice, Integer > implements NoticeDao{

	public Notice deleteById( Integer id ) {
		Notice bean = get( id );
		if( bean != null ){
			getSession( ).delete( bean );
		}
		
		return bean;
	}

	public Notice findById( Integer id ) {
		return get( id );
	}

	public Notice findMyNotice( Integer id, Integer selfId ) {
		String hql = "from Notice bean where bean.id=? and bean.admin.id=?";
		return ( Notice ) findUnique( hql, id, selfId ); 
	}

	public Pagination getPage( Integer selfId, String searchProperty, String searchValue, String orderProperty, String orderDirection, String filterStatus, int pageNo, int pageSize ) {
		Finder f = Finder.create( " from Notice bean where 1=1 " );
		if( selfId != null ){
			f.append( " and bean.admin.id=:id" );
			f.setParam( "id", selfId );
			f.append( " or bean.noticeType.identity=:identity" );
			f.setParam( "identity", "s" );
		}
		
		createFilter( f, filterStatus );
		createSearch( f, searchProperty, searchValue );
		createOrder( f, orderProperty, orderDirection, "id" );
		
		return find( f, pageNo, pageSize );
	}
	
	/**
	 * 根据
	 * @param status
	 * @param pageNo
	 * @param pageSize
	 * @return
	 * 当前用户必须属于当前管理员， 
	 */
	public Pagination getPage(   Integer groupId, List< Integer > idList,  int pageNo, int pageSize ){
		
		StringBuilder sqls = new StringBuilder( );
		sqls.append( "(" );
		for( int i = 0; i < idList.size( ); i++ ){
			
			sqls.append( " admin_id=" );
			sqls.append( idList.get( i ) );
			
			if( i < idList.size( ) - 1 ){
				sqls.append( " or " );
			}
			
		}
		sqls.append( ")" );
	
		
		String sql = "type_id=(select id from trade_noticetype where identity!='s' ) and  " + sqls +  " and find_in_set(" + groupId + ",oriented_group)";
		
		Criteria c = this.createCriteria( sql ); // 创建对象
		createOrder( c, "id", "desc", "id" );
		Pagination p = this.findByCriteria( c, pageNo, pageSize );
		return p;
	}
	
	public Notice getLastNotice( ){
		Query query = createQuery( "from Notice bean where bean.noticeType.identity=? order by bean.addDate desc", "s" );
		query.setMaxResults( 1 );
		query.setCacheable( true ); // 缓存
		return ( Notice )query.uniqueResult( );
	}

	public Notice save( Notice bean ) {
		getSession( ).save( bean );
		return bean;
	}

	@Override
	protected Class< Notice > getEntityClass( ) {
		return Notice.class;
	}

}
